import json


class ConfigManager:
    _default_port = 6789
    _default_hotkeys = {
        "<ctrl>+<f1>": "msg1!",
        "<ctrl>+<f2>": "msg2!",
        "<ctrl>+<f3>": "msg3!"
    }

    @classmethod
    def get_default_port(cls):
        """获取默认的WebSocket服务器端口号"""
        return cls._default_port

    @classmethod
    def get_default_hotkeys(cls):
        """获取默认的热键配置"""
        return cls._default_hotkeys

    @classmethod
    def get_user_port(cls):
        """获取用户自定义的WebSocket服务器端口号(如果有的话)"""
        try:
            with open("user_config.json", "r", encoding='utf-8') as config_file:
                config = json.load(config_file)
                return config.get("port", cls._default_port)
        except (FileNotFoundError, json.JSONDecodeError):
            return cls._default_port
        except Exception as e:
            print(f"发生未知错误: {e}")
            return cls._default_hotkeys

    @classmethod
    def get_user_hotkeys(cls):
        """获取用户自定义的热键配置(如果有的话)"""
        try:
            with open("user_config.json", "r", encoding='utf-8') as config_file:
                config = json.load(config_file)
                return config.get("hotkeys", cls._default_hotkeys)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(e)
            return cls._default_hotkeys
        except Exception as e:
            print(f"发生未知错误: {e}")
            return cls._default_hotkeys

    @staticmethod
    def save_user_config(port=None, hotkeys=None):
        """保存用户自定义的配置到文件"""
        config = {}
        if port is not None:
            config["port"] = port
        if hotkeys is not None:
            config["hotkeys"] = hotkeys

        with open("user_config.json", "w") as config_file:
            json.dump(config, config_file, indent=4)
